<template>
  <el-tabs v-model="editableTabsValue" type="card"  closable @edit="handleTabsEdit" @tab-click="changeRouter">
    <el-tab-pane
        :key="item.name"
        v-for="(item, index) in editableTabs"
        :label="item.title"
        :name="item.name"
    >
    </el-tab-pane>
  </el-tabs>
</template>

<script>
export default {
  name: "Tabs",
  data() {
    return {
      tabIndex: 2
    }
  },
  computed:{
    editableTabsValue:{
      get(){
        return this.$store.state.menus.editableTabsValue;
      },
      set(value){
        this.$store.state.menus.editableTabsValue=value;
      }
    },
    editableTabs:{
      get(){
        return  this.$store.state.menus.editableTabs
      },
      set(value) {
        this.$store.state.menus.editableTabs = value
      }
    }
  },
  methods: {
    handleTabsEdit(targetName, action) {
      if (action === 'add') {
        let newTabName = ++this.tabIndex + '';
        this.editableTabs.push({
          title: 'New Tab',
          name: newTabName,
          content: 'New Tab content'
        });
        this.editableTabsValue = newTabName;
      }
      if (action === 'remove') {
        let tabs = this.editableTabs;
        let activeName = this.editableTabsValue;
        if (targetName==='Index'){
          return;
        }
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name;
              }
            }
          });
        }
        this.editableTabsValue = activeName;
        this.editableTabs = tabs.filter(tab => tab.name !== targetName);
        this.$router.push({name:activeName})
      }
    },
    changeRouter(target){
      this.$router.push({name:target.name});
    }
  }
}
</script>

<style scoped>

</style>